package com.ruoyi.system.util;

import cn.hutool.poi.excel.ExcelWriter;
import com.ruoyi.system.domain.Department;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Auther:尤志杰
 * @Date:2025/3/1 08:40
 * @Description: DownloadExcel
 * @Version 1.0.0
 */
@Component("DownloadExcel")
public class DownloadExcel {

    public void getDownloadExcel(HttpServletResponse response, List<Department> departmentList) throws IOException {
        //构建writer
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        //设置中文表头
        writer.addHeaderAlias("departmentNumber", "部门编号");
        writer.addHeaderAlias("departmentName", "部门名称");
        writer.addHeaderAlias("principal", "负责人");
        writer.addHeaderAlias("mobilePhone", "手机号");
        writer.addHeaderAlias("establishDate", "成立日期");
        writer.addHeaderAlias("revocationDate", "撤销日期");
        writer.addHeaderAlias("remark", "备注");
        //写出数据到writer
        writer.setOnlyAlias(true);
        writer.write(departmentList);
        //设置输出的Excel名称
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("部门信息", "UTF-8");
        Date date = new Date();
        String newDate = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + newDate + ".xlsx");
        //写出到输出流，并关闭writer
        ServletOutputStream sos = response.getOutputStream();
        writer.flush(sos);
        writer.close();
        sos.close();
    }
}
